import React from 'react'
import { UdPageHeader, UdFilter, http, UdDateRangePicker, UdModal, BaseListPage, IBaseListPageProps, IBaseListPageState, columnRenders, validators } from '@/lib/index'
import apis from '@/apis/PurchaseManage'
import { Table, Button, Steps, Select, message } from 'antd';
import './index.scss'
import moment from 'moment';
import { downBlobFile } from '@/utils/methods'
import UdSelect from '@/components/UdFormControls/UdSelect';
import { getBrandSelectList, getDealerListByBrand } from '@/common/Request';

//接口字段映射
const fieldMap = {
  //订单编号
  orderId: "Number",
  //订单类型
  orderType: "SalesOrderTypeName",
  //订单状态
  orderStatus: "OrderStatusName",
  //审批状态
  approvalStatus: "TaskLevelStatusName",
  //送达方
  sendTo: "ReceiveCustomerName",
  //下单时间
  time: "AddTime",
  //数量
  number: "TotalAmount",
  //应付金额
  amountsPayable: "Money",
  //销售金额
  salesAmount: "SalesMoney",

  //详情 - 交货单号
  detailsOrderNumber: "deliveryNumber",
  //详情 - 数量
  detailsNumber: "detailsNumber",
  //详情 - 发货日期
  detailsDate: "detailsDate",
  //详情 - 物流编号
  detailsLogisticsNumber: "detailsLogisticsNumber",
  //详情 - 是否签收
  detailsIsReceipt: "detailsIsReceipt",
  //详情 - 备注
  detailsRemark: "detailsRemark",

  //明细 - 商品名称
  modalDetailsName: "modalDetailsName",
  //明细 - 商品数量
  modalDetailsNumber: "modalDetailsNumber",
  //明细 - 计量单位
  modalDetailsUnit: "modalDetailsUnit",

  //审批状态 未进入
  noOn: 1,
  //审批状态 流程中
  onLine: 2,
  //审批状态 被终止
  haveEnd: 3,
  //审批状态 已完成
  done: 4,

  //详情 - 是否签收 - 未签收
  noReceipt: 1,
  //详情 - 是否签收 - 已签收
  haveReceipt: 2,

  //下拉框传递值
  value: "value",
  //下拉框显示值
  name: "name",
}

//按钮权限
// const addAuth = ""

export default class List extends BaseListPage<IPurchaseListProps, IPurchaseListState> {

  constructor(props) {
    super(props)
    this.state = {
      title: '进货订单列表',
      queryApi: (params) => {
        params.BrandCodes = [params.BrandCodes]
        return http.post(apis.getPurchaseList, params)
      },
      rowKey: fieldMap.orderId,
      conditions: [
        {
          id: "BrandCodes", label: "销售组织", rules: [validators.required], render: () => {
            return (
              <UdSelect onChange={this.getDealerListByBrand} options={this.state.brandOptions} allowClear={false} />
            )
          }
        },
        {
          id: "dealerCode", label: "经销商", rules: [validators.required], render: () => {
            return (
              <UdSelect options={this.state.dealerOptions} showSearch={true} allowClear={false} />
            )
          }
        },
        {
          id: fieldMap.orderId,
          label: "订单编号"
        },
        {
          id: 'SalesOrderTypeCode',
          label: "订单类型",
          render: <Select>
            <Select.Option value={"ZGB1"}>优选标准销售订单</Select.Option>
            <Select.Option value={"ZQQ1"}>标准订单</Select.Option>
            <Select.Option value={"ZKH1"}>标准销售订单</Select.Option>
          </Select>
        },
        {
          id: 'OrderStatus',
          label: "订单状态",
          render: <Select >
            <Select.Option value="INITIAL_CREATION">初始创建</Select.Option>
            <Select.Option value='SEND_ERP'>已发送到ERP</Select.Option>
            <Select.Option value="SEND_ERP_AND_LOGISTICS">已发送ERP并发送物流</Select.Option>
            <Select.Option value="REVOKED">订单已撤销</Select.Option>
          </Select>
        },
        {
          id: 'TaskLevelStatus',
          label: "审批状态",
          render: <Select >
            <Select.Option value='NOT_ENTERED'>未进入</Select.Option>
            <Select.Option value='IN_PROCESS'>流程中</Select.Option>
            <Select.Option value='COMPLETED'>已完成</Select.Option>
            <Select.Option value='TERMINATED'>被终止</Select.Option>
          </Select>
        },
        {
          id: "ReceiveCustomerName",
          label: "送达方",
        },
        {
          id: ['BeginTime', 'EndTime'],
          label: "下单时间",
          render: <UdDateRangePicker />
        }
      ],
      columns: [
        {
          dataIndex: "sort",
          title: "序号",
          render: (text, record, index) => index + 1
        },
        {
          dataIndex: "SalesOrganizationName",
          title: "销售组织"
        },
        {
          dataIndex: fieldMap.orderId,
          title: "订单编号"
        },
        {
          dataIndex: fieldMap.orderType,
          title: "订单类型"
        },
        {
          dataIndex: fieldMap.number,
          title: "数量"
        },
        {
          dataIndex: fieldMap.amountsPayable,
          title: "应付金额",
          align: 'right'
        },
        {
          dataIndex: fieldMap.salesAmount,
          title: "销售金额",
          align: 'right'
        },
        {
          dataIndex: fieldMap.sendTo,
          title: "送达方"
        },
        {
          dataIndex: fieldMap.orderStatus,
          title: "订单状态"
        },
        {
          dataIndex: fieldMap.approvalStatus,
          title: "审批状态"
        },
        {
          dataIndex: fieldMap.time,
          title: "下单时间",
          render: (text, record, index) => text ? moment(text).format("YY-MM-DD HH:mm:ss") : ""
        },
        {
          dataIndex: "dos",
          title: "操作",
          fixedWidth: '120px',
          fixed: 'right',
          render: columnRenders.operate([
            { title: '查看详情', action: (text, record) => this.handleDetails(record[fieldMap.orderId]) },
            { title: '物流跟踪', action: (text, record) => this.transportTrack(record[fieldMap.orderId]) }
          ])
        }
      ],
      leftBtns: [
        <Button type='primary' onClick={this.handleExportList}>导出</Button>,
      ],
      tableProps: {
        scroll: { x: true },
        className: 'nowarp',
        rowSelection: null,
      },
      brandOptions: [],
      dealerOptions: [],
    }
  }
  
  componentDidMount() {
    this.getBrandList()
    const { BrandCodes, dealerCode } = this.queryParams.conditions
    if (BrandCodes && dealerCode) {
      this.getDealerListByBrand(BrandCodes)
      super.componentDidMount()
    }
  }

  transportTrack = (orderId: any) => {
    http.get(apis.viewLogisticsOrder, {
      params: {
        code: orderId,
        type: 'AL',
      }
    }).then(({ data }: any) => {
      window.open(data)
    })
  }

  private getBrandList = () => {
    getBrandSelectList().then((result: any) => {
      this.setState({
        brandOptions: result,
      })
    })
  }

  private getDealerListByBrand = (code) => {
    // 组织切换，重置经销商条件
    this.filterForm.setFieldsValue({ dealerCode: undefined })
    getDealerListByBrand(code).then((result: any) => {
      this.setState({
        dealerOptions: result,
      })
    })
  }

  protected filterReset = () => {
    this.setState({
      dataSource: [],
    })
  }

  //查看详情
  private handleDetails = (id) => {
    const { dealerCode } = this.queryParams.conditions
    this.props.history.push({
      pathname: `/purchase-management/details/${id}`,
      search: `dealerCode=${dealerCode}`
    })
  }

  //导出
  private handleExportList = () => {
    const params = this.queryParams.conditions
    params.BrandCodes = [params.BrandCodes]
    if (!params.dealerCode || !params.BrandCodes) {
      message.error('请选择销售组织和经销商查询后操作')
      return
    }
    http.post(apis.exportPurchase, params, {
      responseType: "arraybuffer"
    }
    ).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, "进货订单列表")
      }
    })
  }
}

const DetailsTable = (props) => {
  //交货单明细
  const handleOrderDetails = (id) => {
    UdModal.open({
      width: "600px",
      title: "交货单明细",
      content: <>
        <ul style={{ listStyle: "none", paddingInlineStart: "5px" }}>
          <li style={{ padding: "5px 0px" }}><span>交货单号：</span><span>{}000000001</span></li>
          <li style={{ padding: "5px 0px" }}><span>商品数量：</span><span>{}30件</span></li>
          <li style={{ padding: "5px 0px" }}><span>发货日期：</span><span>{}2019-08-01</span></li>
          <li><span>物流编号：</span><span>{}000000022</span><Button type="link" onClick={() => { handleLogistics(id) }}>物流详情＞</Button></li>
        </ul>
        <Table
          rowKey={(record, index) => index + ""}
          dataSource={[]}
          columns={[
            {
              dataIndex: "sort",
              title: "序号",
              render: (text, record, index) => index + 1
            },
            {
              dataIndex: fieldMap.modalDetailsName,
              title: "商品名称"
            },
            {
              dataIndex: fieldMap.modalDetailsNumber,
              title: "商品数量"
            },
            {
              dataIndex: fieldMap.modalDetailsUnit,
              title: "计量单位"
            }
          ]}
          pagination={false}
        />
      </>,
      okText: "一键入库",
      cancelText: "关闭",
      onOk: () => { }
    })
  }

  //物流跟踪
  const handleLogistics = (id) => {

    const data = [
      {
        titlt: "物流详情1",
        description: "2016-09-25 09:50:08"
      },
      {
        titlt: "物流详情1",
        description: "2016-09-25 09:50:08"
      },
      {
        titlt: "物流详情1",
        description: "2016-09-25 09:50:08"
      },
      {
        titlt: "物流详情1",
        description: "2016-09-25 09:50:08"
      }
    ]

    UdModal.open({
      title: "物流跟踪",
      content: <>
        <div style={{ fontSize: "16px", paddingBottom: "10px" }}><span>物流公司：</span>{}中通快递</div>
        <div style={{ fontSize: "16px", paddingBottom: "15px" }}><span>物流编号：</span>{}2222222222222222</div>
        <Steps progressDot current={0} direction="vertical">
          {
            data.map((item, index) => <Steps.Step title={item.titlt} description={item.description} key={index} />)
          }
        </Steps>
      </>,
      footer: null
    })
  }

  //货物签收
  const handleReceipt = (id) => {

  }

  return <Table
    rowKey={(record, index) => index + ""}
    dataSource={[]}
    columns={[
      {
        dataIndex: "sort",
        title: "序号",
        render: (text, record, index) => index + 1
      },
      {
        dataIndex: fieldMap.detailsOrderNumber,
        title: "交货单号"
      },
      {
        dataIndex: fieldMap.detailsNumber,
        title: "数量"
      },
      {
        dataIndex: fieldMap.detailsDate,
        title: "发货日期"
      },
      {
        dataIndex: fieldMap.detailsLogisticsNumber,
        title: "物流编号"
      },
      {
        dataIndex: fieldMap.detailsIsReceipt,
        title: "是否签收",
        render: (text, record, index) => text === fieldMap.noReceipt ? "未签收" : text === fieldMap.haveReceipt ? "已签收" : ""
      },
      {
        dataIndex: fieldMap.detailsRemark,
        title: "备注",
        render: (text, record, index) => record[fieldMap.detailsRemark] ? text : "/"
      },
      {
        dataIndex: "dos",
        title: "操作",
        render: (text, record: any, index) => <>
          <Button type="link" onClick={() => { handleOrderDetails(record.id) }}>交货单明细</Button>
          <Button type="link" onClick={() => { handleLogistics(record.id) }}>物流跟踪</Button>
          {
            record[fieldMap.detailsIsReceipt] === fieldMap.noReceipt &&
            <Button type="link" onClick={() => { handleReceipt(record.id) }}>货物签收</Button>
          }
        </>
      }
    ]}
    pagination={false}
  />
}

interface IPurchaseListProps extends IBaseListPageProps {

}

interface IPurchaseListState extends IBaseListPageState {
  brandOptions: any[]
  dealerOptions: any[]
}